package com.psp.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tiger
 */
public class StockUtils {

    public static Logger logger = LoggerFactory.getLogger(StockUtils.class);
    // 新浪接口
    public static String sinaUrl = "http://hq.sinajs.cn/list=";

    /**
     * 从百度获取股票历史价格
     *
     * @param code 股票编码
     * @return 股票收盘价格, 格式[["2017-01-03",0.897],["2017-01-04",0.904]]
     */
    public static List<List<String>> getStockClosePriceByBaidu(String code) {
        String url;
        if (code.equals("-1")) {
            //上证指数
            url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=8190&from_mid=1&query=%E4%B8%8A%E8%AF%81%E6%8C%87%E6%95%B0&eprop=year";
        } else {
            url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=5353&all=1&pointType=string&group=quotation_kline_ab&ktype=1&query=" + code + "&code=" + code + "&ktype=1&word=" + code + "&format=json&from_mid=1&oe=utf-8&dsp=pc&tn=wisexmlnew&need_di=1&all=1&query=" + code + "&eprop=dayK&euri=undefined&request_type=sync&stock_type=ab&sid=33814_31253_34004_33607_26350_22157";
        }

        String response;
        try {
            response = HttpRequest.get(url).timeout(3000).execute().body();
        } catch (Exception e) {
            logger.error("爬取股票价格失败!");
            e.printStackTrace();
            return null;
        }

        List<List<String>> result = new ArrayList<>(200);

        try {
//            ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
            JSONObject jsonObject = JSON.parseObject(response);

            JSONObject r = jsonObject.getJSONArray("Result").getJSONObject(0).getJSONObject("DisplayData")
                    .getJSONObject("resultData")
                    .getJSONObject("tplData")
                    .getJSONObject("result");

            //股票日期和价格
            String stockPriceStr = r.get("p").toString();

            String[] stockPriceArray = stockPriceStr.split(";");
            for (String p : stockPriceArray) {
                String[] tmp = p.split(",");
                List<String> tmpList = new ArrayList<>();
                //股票交易日期
                tmpList.add(tmp[0].replaceAll("/", "-"));
                //开盘价格
                tmpList.add(tmp[1]);
                //收盘价格
                tmpList.add(tmp[4]);
                //最高价
                tmpList.add(tmp[2]);
                //最低价
                tmpList.add(tmp[3]);
                //成交量
                if (tmp[5].endsWith("万")) {
                    tmp[5] = tmp[5].substring(0, tmp[5].length() - 1);
                    tmp[5] = String.valueOf(Double.parseDouble(tmp[5]) * 10000);
                }
                tmpList.add(tmp[5]);
                result.add(tmpList);
            }
        } catch (Exception e) {
            logger.error("截取股票价格失败!");
            e.printStackTrace();
            return null;
        }

        logger.debug("截取股票价格成功!");
        return result;
    }

    /**
     * 从新浪获取每日股票价格,注意开盘之前获取的价格是0
     *
     * @param code 例:<a href="http://hq.sinajs.cn/list=sz000002">...</a>,返回格式var hq_str_sz000002="万 科Ａ,28.050,28.020,28.030,28.290,27.740,28.030,28.040,68434585,1913388242.740,186381,28.030,77500,28.020,14800,28.010,114400,28.000,26200,27.990,16200,28.040,22300,28.050,14700,28.060,6200,28.070,11700,28.080,2020-10-09,15:00:03,00";
     *             数值依次是今日开盘价、昨日收盘价、当前价、今日最高价、今日最低价
     * @return 股票价格, 依次是日期、开盘、收盘、最高、最低
     */
    public static String[] getStockPriceBySina(String code) {
        try {
            String response = GetResponse.getResponse(sinaUrl + code, "GBK");
//            System.out.println(response);
            response = response.substring(response.indexOf(",") + 1, response.length() - 2);
            String[] tmp = response.split(",");
            String[] price = new String[7];
            price[0] = tmp[29];  //日期
            price[1] = tmp[0];   //开盘价
            price[2] = tmp[2];   //收盘价
            price[3] = tmp[3];   //最高价
            price[4] = tmp[4];   //最低价
            price[5] = String.valueOf(Double.parseDouble(tmp[7]) / 100);   //成交量
            price[6] = tmp[8];   //成交额
            logger.debug("截取股票价格成功!");
            return price;
        } catch (Exception e) {
            logger.error("爬取股票价格失败!");
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {

//        System.out.println("从百度获取上交所-招商银行一年内的股票价格");
//        System.out.println(getStockClosePriceByBaidu("600036"));
//        System.out.println(getStockClosePriceByBaidu("159865"));

//        System.out.println("从新浪获取每日股票价格");
//        System.out.println(JSON.toJSONString(getStockPriceBySina("sh600036")));
//        System.out.println(JSON.toJSONString(getStockPriceBySina("sz301202")));
        System.out.println(JSON.toJSONString(getStockPriceBySina("sz000001")));
//        System.out.println(JSON.toJSONString(getStockPriceBySina("sz000006")));

//        System.out.println(GetResponse.getResponse("http://api.mairui.club/hslt/list/61400165679d0a013","UTF-8"));

//        String result2= HttpRequest.get("http://hq.sinajs.cn/list=sz000002")
//                .header(Header.REFERER,"https://finance.sina.com.cn/").execute().body();
//        System.out.println(result2);


    }
}
